#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

pthread_rwlock_t lock;
int data;

void* rdfunc(void*);
void* wrfunc(void*);

int main(int argc,char** argv) 
{
  pthread_rwlock_init(&lock,NULL);
  pthread_attr_t attr;
  pthread_attr_init(&attr);
  pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
  
  pthread_t tid;
  for(int i = 0;i < 5;i++)
  {
    pthread_create(&tid,&attr,rdfunc,(void*)i);
  }
  
  for(int i = 0;i < 3;i++)
  {
    pthread_create(&tid,&attr,wrfunc,(void*)i);
  }

  pthread_attr_destroy(&attr);
  pthread_rwlock_destroy(&lock);
  
  pthread_exit((void*)0); 
}

void* rdfunc(void* num)
{
  int i = (int)num;
  int ret;
  while(1)
  {
    ret = pthread_rwlock_tryrdlock(&lock);
    if(ret == 0)
    {
      printf("read i = %d,data = %d\n",i,data);
      pthread_rwlock_unlock(&lock);
      usleep(400);
    }
  }
  return NULL;
}

void* wrfunc(void* num)
{
  int i = (int)num;
  int ret;
  while(1)
  {
    ret = pthread_rwlock_trywrlock(&lock);
    if(ret == 0)
    {
      data = i;
      printf("write i = %d.data = %d\n",i,data);
      pthread_rwlock_unlock(&lock);
      usleep(200);
    }
  }
  return NULL;
}

